import api from './global.js'

let userUrl = '/treeHole/user.action'
let articleUrl = '/treeHole/article.action'
let commentUrl = '/treeHole/comment.action'
let reportUrl = '/treeHole/reportLabel.action'
let qrcodeTime = 60 * 14;
let timingQrcode;

const validateOldPass = async (rule, value, callback) => {
    if (value === "") {
        callback(new Error("请输入旧密码"));
    } else {
        let params = new URLSearchParams();
        params.append("op", "checkUserPwd");
        params.append("password", vm.$data.userPawInforform.oldPaw);
        const {
            data: res
        } = await axios.post(userUrl, params);
        if (!res.data) {
            callback(new Error("密码错误"));
            vm.$data.isOldPaw = false
            return
        }
        vm.$data.isOldPaw = true
        callback();
    }
};


let vm = new Vue({
        el: "#app",
        data: {
            oneArticleComment: false,//单篇文章评论窗口
            valCode: '',
            articleLabels: '',
            articleContent: '',
            audit: false,
            published: false,
            userAvatarUrl: "",
            userName: "",
            userId: "",
            isEdit: false,
            userIndex: 1,
            userIsLogin: false,
            upload_url: 'upload',
            personalCenter: false,
            articleData: [], //首页文章信息
            user_comments: [],  //用户评论管理
            article_comments: [], //首页文章评论
            articleComments: [],//单篇文章评论
            oneArticle: {}, //单篇文章信息
            money: 5,
            isShowTooltip: false,
            qrCode: '',
            orderId: '',
            myHeaders: {
                Authorization: "",
            },
            userInfoById: {},
            changePawFormRules: {
                oldPaw: [{
                    required: true,
                    message: "请输入旧密码",
                    trigger: "blur"
                }, {
                    min: 5,
                    max: 11,
                    message: "请输入5~11位字符密码！",
                    trigger: "blur",
                }, {
                    validator: validateOldPass,
                    trigger: "blur"
                },

                ],
                newPaw: [{
                    required: true,
                    message: "请输入新密码",
                    trigger: "blur"
                },
                    {
                        min: 5,
                        max: 11,
                        message: "请输入5~11位字符密码！",
                        trigger: "blur",
                    },
                ],
            },
            userPawInforform: {
                oldPaw: '',
                newPaw: '',
            },
            isOldPaw: false,
            searchText: '',  //搜索的关键字
            user_commentCount: 0,
            index_curPage: 1,//首页的文章分页
            index_article_total: 0,
            //走马灯栏图片路径
            carousel_url: [
                'http://121.4.192.88:9876/image/treeHole/user/card/card-1.jpeg',
                'http://121.4.192.88:9876/image/treeHole/user/card/card-2.jpeg',
                'http://121.4.192.88:9876/image/treeHole/user/card/card-3.jpeg',
                'http://121.4.192.88:9876/image/treeHole/user/card/card-4.jpeg',
                'http://121.4.192.88:9876/image/treeHole/user/card/card-5.jpeg',
                'http://121.4.192.88:9876/image/treeHole/user/card/card-6.jpeg',
            ],
            classify_index: 1,//侧边栏的索引
            auditArticle: {},//待审核的文章
            hasNewAuditArticle: false,//是否有新待审核的文章
            activeName: 'first',
            articleIsLoading: true,//懒加载
            qrCodeIsLoading: true,
            commentInput: '',
            commentProps: {
                children: 'childComment',
                label: 'commentContent',
            },
            replyDrawer: false,//评论回复的窗口
            replyInput: '',//评论回复输入
            parentData: {},//父评论数据
            parentUserName: '',//父评论用户
            ownerComments: [],//自己的全部评论
            ownerCommentsTotal: 0,//自己的全部评论的总数
            ownerArticleComments: [],//自己文章的全部评论，包括自己的
            ownerArticleCommentsTotal: 0,//自己文章的全部评论，包括自己的总的总数
            ownerCommentCurPage: 1,//自己评论的分页
            ownerArticlesPass: [],//自己根据文章是否审核查询的文章
            ownerArticlesNotPass: [],//自己根据文章是否审核查询的文章
            ownerArticlesCurPage: 1, //文章管理当前的页数
            ownerArticlesTotal: 0,
            valIndex: 1,//发表文章时候的延迟加载验证码
            reportDialogVisible: false,//文章举报的窗口显示
            allReportLabelsList: [],//所有的举报标签
            childReportLabelsList: [],//次级举报标签
            insert_label: '', //举报标签
            chooice: '',//一级举报标签
            secondChooice: '',//二级举报标签
            insertReason: '',//举报原因
            insertCommentId: '',//举报id
            insertcommentContent: '',//举报内容
            currentBrowse: [],//存储当前已经浏览的文章ID
            currentLabel: '',//当前用户评论的标签
            webscoketIp: '',
            isOwnFace: true,
            openFail: false,
            searchLabel: '',
        },
        methods: {
            open(articleContent) {
                let thiss = this;
                articleContent = articleContent.substring(0, 50) + '...';
                this.$notify({
                    title: '有新秘密已经寄存(点击可查看详情)',
                    dangerouslyUseHTMLString: true,
                    message: '<span style="cursor: pointer;">' + articleContent + '</span>',
                    duration: 1000 * 30,
                    onClick() {
                        thiss.index_curPage = 1;
                        thiss.classify_index = "3";
                        thiss.jumpTheNewArticle();
                    }
                });
            },
            jumpTheNewArticle() {
                this.getArticleBySome("new", null, null);
            },

            initWebSocket() { // 初始化weosocket
                this.websock = new WebSocket('ws://121.4.192.88:9876/treeHole/websocket');
                // this.websock = new WebSocket('ws://localhost:8080/treeHole/websocket');
                this.websock.onmessage = this.websocketonmessage;
                // this.websock.onerror = this.websocketonerror;
                this.websock.onopen = this.websocketonopen;
                // this.websock.onclose = this.websocketclose;
            }
            ,
            websocketonopen() { // 连接建立之后执行send方法发送数据
                let userId = api.getCookie("loginUser.userId");
                if (userId != null || userId != '' || userId.length > 0) {
                    this.websocketsend(userId);
                } else {
                    this.websocketsend("null");
                }
            }
            ,
// websocketonerror() {
//     console.log('WebSocket连接失败')
// },
            websocketonmessage(e) { // 数据接收
                let params = new URLSearchParams();
                params.append("op", "getOne");
                params.append("articleId", e.data);
                axios.post(articleUrl, params).then(res => {
                    if (res.data.code == '200') {
                        this.open(res.data.data.articleContent);
                        // console.log(res.data)
                    }
                });
            }
            ,
            websocketsend(message) { // 数据发送
                this.websock.send(message)
            }
            ,
// websocketclose(e) {  // 关闭
//     console.log('已关闭连接', e)
// },
//回到顶部
            smoothscroll() {
                document.body.scrollTop = 388;
                document.documentElement.scrollTop = 388;
            }
            ,
//获取用户的猜他喜欢
            getUserMayBeLike() {
                let params = new URLSearchParams();
                params.append("op", "recommended");
                params.append("userId", this.userId);
                axios.post(articleUrl, params).then(res => {
                    this.articleData = res.data.data.articles;
                    this.articleIsLoading = false;
                });
            }
            ,
            getUserMayBeLikeAndsmoothscroll() {
                this.getUserMayBeLike();
                this.smoothscroll();
            }
            ,
            increUserBrowse(row, type) {
                if (type == 1) {
                    let len = this.currentBrowse.length;
                    if (len > 0) {
                        for (let i = 0; i < len; i++) {
                            if (this.currentBrowse[i] == row.articleId) {
                                return;
                            }
                        }
                    }
                    this.currentBrowse.push(row.articleId);
                }
                let params = new URLSearchParams();
                params.append("op", "browse");
                params.append("userId", this.userId);
                params.append("articleLabel", row.articleLabel);
                axios.post(articleUrl, params);
            }
            ,
//当选择表格的行触发的事件
            tableRowClick(row, column, event) {
                if (this.userIsLogin == false) {
                    return;
                }
                this.increUserBrowse(row, 1);
            }
            ,
//获取所有的举报标签
            getAllReportLabels() {
                let params = new URLSearchParams();
                params.append("op", "getAllReportLabel")
                axios.post(reportUrl, params).then(res => {
                    if (res.data.code == '200') {
                        this.allReportLabelsList = res.data.data;
                        res.data.data.forEach((item) => {
                            this.childReportLabelsList.push(item.childLabel)
                        })
                    }
                });
            }
            ,
//确定举报
            sendInsertInfo() {

            }
            ,
//一级举报原因点击
            insertLabelclick(reportId) {
                this.chooice = reportId
            }
            ,
//二级举报原因点击
            insertSecondLabelclick(reportId) {
                this.secondChooice = reportId
            }
            ,
            tableRowClassName({row, rowIndex}) {
                if (rowIndex % 2 == 1) {
                    return 'warning-row';
                } else if (rowIndex % 2 == 0) {
                    return 'success-row';
                }
                return '';
            }
            ,
//当用户进行删除文章的时候，进行重新发起请求
            refreshArticle() {
                let type;
                let flag = false;
                if (this.classify_index == "1") {
                    type = "hot";
                    flag = true;
                } else if (this.classify_index == "2-1") {
                    type = "essence-24";
                    flag = true;
                } else if (this.classify_index == "2-2") {
                    type = "essence-7";
                    flag = true;
                } else if (this.classify_index == "2-3") {
                    type = "essence-30";
                    flag = true;
                } else if (this.classify_index == "3") {
                    type = "new";
                    flag = true;
                }
                if (flag == true) {
                    this.getArticleBySome(type, null, null);
                }
            }
            ,
            handleDelete4(index, row) {
                this.$refs[row.articleId].doClose();
                this.deleteArticleById(row.articleId, 0);
            }
            ,
            handleDelete3(index, row) {
                this.$refs[row.articleId].doClose();
                this.deleteArticleById(row.articleId, 1);
            }
            ,
//通过文章ID删除文章
            deleteArticleById(articleId, type) {
                let params = new URLSearchParams();
                params.append("op", "delete");
                params.append("articleId", articleId);
                axios.post(articleUrl, params).then(res => {
                    if (res.data.code != '200') {
                        this.$message({
                            type: 'error',
                            message: '删除失败！',
                            center: true
                        });
                    } else {
                        this.$message({
                            type: 'success',
                            message: '删除成功！',
                            center: true
                        });
                        this.refreshArticle();
                        if (type == '1') {
                            this.getOwnerArticleByType(1);
                        } else {
                            this.getOwnerArticleByType(0);
                        }
                    }
                });
            }
            ,
//通过类型获取自己的文章
            getOwnerArticleByType(type) {
                let params = new URLSearchParams();
                params.append("op", "getOwnerArticle");
                params.append("type", type);
                params.append("curPage", this.ownerArticlesCurPage);
                axios.post(articleUrl, params).then(res => {
                    res.data.data.articles.forEach((item) => {
                        item.simpleComtent = item.articleContent;
                        item.simpleComtent = item.simpleComtent.replaceAll("&emsp;", '  ');
                        item.simpleComtent = item.simpleComtent.replaceAll("<br/>", '\n');
                        item.simpleComtent = item.simpleComtent.substring(0, 40) + " ...";
                    });
                    if (type == 1) {
                        this.ownerArticlesPass = res.data.data.articles;
                    } else {
                        this.ownerArticlesNotPass = res.data.data.articles;
                    }
                    this.ownerArticlesTotal = res.data.data.total;
                });
            }
            ,
            handleDelete2(index, row) {
                this.$refs[row.commentId].doClose();
                let commentId = row.commentId;
                let params = new URLSearchParams();
                params.append("op", "delete");
                params.append("commentId", commentId);
                axios.post(commentUrl, params).then(res => {
                    if (res.data.code == '200') {
                        this.$message({
                            type: 'success',
                            message: '删除成功！',
                            center: true
                        });
                        let articleId = row.articleId;
                        let commentCount = res.data.data.commentCount;
                        let len = this.articleData.length;
                        for (let i = 0; i < len; i++) {
                            if (this.articleData[i].articleId == articleId) {
                                this.articleData[i].articleCommentCount = commentCount;
                                break;
                            }
                        }
                        this.getOwnerComments();
                    } else {
                        this.$message({
                            type: 'error',
                            message: '删除失败！',
                            center: true
                        });
                    }
                });
            }
            ,
            handleDelete1(index, row) {
                this.$refs[row.commentId].doClose();
                let commentId = row.commentId;
                let params = new URLSearchParams();
                params.append("op", "delete");
                params.append("commentId", commentId);
                axios.post(commentUrl, params).then(res => {
                    if (res.data.code == '200') {
                        this.$message({
                            type: 'success',
                            message: '删除成功！',
                            center: true
                        });
                        let articleId = row.articleId;
                        let commentCount = res.data.data.commentCount;
                        let len = this.articleData.length;
                        for (let i = 0; i < len; i++) {
                            if (this.articleData[i].articleId == articleId) {
                                this.articleData[i].articleCommentCount = commentCount;
                                break;
                            }
                        }
                        this.getOwnerArticleComments();
                    } else {
                        this.$message({
                            type: 'error',
                            message: '删除失败！',
                            center: true
                        });
                    }
                });
            }
            ,
            handleCurrentChange1(val) {
                this.getOwnerArticleByType(1);
            }
            ,
            handleCurrentChange2() {
                this.getOwnerArticleByType(0);
            }
            ,
            handleCurrentChange4(val) {
                this.getOwnerComments();
            }
            ,
            handleCurrentChange3(val) {
                this.getOwnerArticleComments();
            }
            ,
//切换文章标签
            toggleTheCommentTAB1(e) {
                this.ownerArticlesCurPage = 1;
                if (e.index == '0') {
                    //通过审核的文章
                    this.getOwnerArticleByType(1);
                } else if (e.index == '1') {
                    //没有通过审核的文章
                    this.getOwnerArticleByType(0);
                }
            }
            ,
//切换评论标签
            toggleTheCommentTAB(e) {
                this.ownerCommentCurPage = 1;
                if (e.index == '0') {
                    //全部的评论
                    this.getOwnerArticleComments();
                } else if (e.index == '1') {
                    //自己的评论
                    this.getOwnerComments();
                }
            }
            ,
//获取自己的全部评论
            getOwnerComments() {
                let params = new URLSearchParams();
                params.append("op", "getOwnerComments");
                params.append("curPage", this.ownerCommentCurPage);
                axios.post(commentUrl, params).then(res => {
                    if (res.data.code != '200') {
                        this.$message({
                            type: 'error',
                            message: '获取评论失败！',
                            center: true
                        });
                        return;
                    } else {
                        this.ownerComments = res.data.data.collect;
                        this.ownerCommentsTotal = res.data.data.total;
                        this.ownerComments.forEach((item) => {
                            item.simpleComtent = item.commentContent.substring(0, 30) + " ...";
                        });
                    }
                });
            }
            ,
//获取自己文章的全部评论
            getOwnerArticleComments() {
                let params = new URLSearchParams();
                params.append("op", "getOwnerArticleComments");
                params.append("curPage", this.ownerCommentCurPage);
                axios.post(commentUrl, params).then(res => {
                    if (res.data.code != '200') {
                        this.$message({
                            type: 'error',
                            message: '获取评论失败！',
                            center: true
                        });
                        return;
                    } else {
                        this.ownerArticleComments = res.data.data.collect;
                        this.ownerArticleCommentsTotal = res.data.data.total;
                        this.ownerArticleComments.forEach((item) => {
                            item.simpleComtent = item.commentContent.substring(0, 30) + " ...";
                        });
                    }
                });
            }
            ,
//发送回复评论请求
            reply() {
                if (this.replyInput == null || this.replyInput.trim() == '') {
                    return;
                }
                let params = new URLSearchParams();
                params.append("op", "insert");
                params.append("articleId", this.parentData.articleId);
                params.append("commentContent", this.replyInput);
                params.append("parentCommentId", this.parentData.commentId);
                axios.post(commentUrl, params).then(res => {
                    if (res.data.code == '500') {
                        this.$message({
                            type: 'error',
                            message: res.data.message,
                            center: true
                        });
                        this.oneArticleComment = false;
                        return;
                    }
                    if (res.data.data.isInsertOk == true) {
                        let commentCount = res.data.data.commentCount;
                        let len = this.articleData.length;
                        for (let i = 0; i < len; i++) {
                            if (this.articleData[i].articleId == this.parentData.articleId) {
                                this.articleData[i].articleCommentCount = commentCount;
                                break;
                            }
                        }
                        this.replyInput = '';
                        this.replyDrawer = false;
                        this.$message({
                            type: 'success',
                            message: '回复成功！',
                            center: true
                        });
                        let params = new URLSearchParams();
                        params.append("op", "getOne");
                        params.append("articleId", this.parentData.articleId);
                        axios.post(commentUrl, params).then(res => {
                            this.articleComments = res.data.data.CommentModels;
                        });

                    } else {
                        this.$message({
                            type: 'error',
                            message: '回复失败！',
                            center: true
                        });
                    }
                });

                let row = {};
                row.articleLabel = this.currentLabel;
                this.increUserBrowse(row, 2);
            }
            ,
            openReply(node, data) {
                if (this.userIsLogin == false) {
                    this.$message.error("请先登录再进行此操作");
                    return;
                }
                this.parentData = data;
                this.parentUserName = data.userToken.userName;
                this.replyDrawer = true;
            }
            ,
//回复功能
            openReply2(node, data) {
                this.$prompt('回复：' + data.userToken.userName, {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',

                }).then(({value}) => {
                    if (value == null || value.trim() == '') {
                        return;
                    }
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '取消回复'
                    });
                });
            }
            ,
//进行文章评论（登录）
            addArticleComment() {
                if (this.userIsLogin == false) {
                    this.$message.error("请先登录再进行此操作");
                    return;
                }
                if (this.commentInput.trim() == '') {
                    return;
                }

                let params = new URLSearchParams();
                params.append("op", "insert");
                params.append("articleId", this.oneArticle.articleId);
                params.append("commentContent", this.commentInput);
                axios.post(commentUrl, params).then(res => {
                    if (res.data.code == '500') {
                        this.$message({
                            type: 'error',
                            message: res.data.message,
                            center: true
                        });
                        this.oneArticleComment = false;
                        return;
                    }
                    if (res.data.data.isInsertOk == true) {
                        let commentCount = res.data.data.commentCount;
                        let len = this.articleData.length;
                        for (let i = 0; i < len; i++) {
                            if (this.articleData[i].articleId == this.oneArticle.articleId) {
                                this.articleData[i].articleCommentCount = commentCount;
                                break;
                            }
                        }
                        this.commentInput = '';
                        this.$message.success("评论成功");
                        let params = new URLSearchParams();
                        params.append("op", "getOne");
                        params.append("articleId", this.oneArticle.articleId);
                        axios.post(commentUrl, params).then(res => {
                            this.articleComments = res.data.data.CommentModels;
                        });

                    } else {
                        this.$message.error("评论失败");
                    }
                });
                let row = {};
                row.articleLabel = this.currentLabel;
                this.increUserBrowse(row, 2);
            }
            ,

//打开单篇文章评论窗口
            openOneArticleComment(row) {
                this.currentLabel = row.articleLabel;
                this.oneArticle = row;
                this.oneArticleComment = true;
                let params = new URLSearchParams();
                params.append("op", "getOne");
                params.append("articleId", row.articleId);
                axios.post(commentUrl, params).then(res => {
                    this.articleComments = res.data.data.CommentModels;
                });
            }
            ,
//通过文章标签获取文章
            getArticleByLabel(label) {
                this.searchLabel = label;
                this.index_curPage = 1;
                let params = new URLSearchParams();
                params.append("op", "getArticleByLabel");
                params.append("label", label);
                params.append("curPage", this.index_curPage);
                axios.post(articleUrl, params).then(res => {
                    if (res.data.data.total == 0) {
                        this.$message.info("---很抱歉，没有相关数据!---");
                    } else {
                        this.classify_index = 7;
                        this.index_article_total = res.data.data.total;
                        this.articleData = res.data.data.article;
                    }
                });
            }
            ,
//文章点赞
            articleUp(row) {
                if (row.articleIsDown == true) {
                    this.$message.error("请取消踩赞后再进行点赞");
                    return;
                }
                let articleId = row.articleId;
                let params = new URLSearchParams();
                params.append("op", "articleUp");
                params.append("articleId", articleId);
                axios.post(articleUrl, params).then(res => {
                    if (res.data.code == '500') {
                        this.$message.error(res.data.message);
                        return;
                    } else {
                        let articleUpCount = res.data.data;
                        let len = this.articleData.length;
                        for (let i = 0; i < len; i++) {
                            if (this.articleData[i].articleId == articleId) {
                                this.articleData[i].articleUpCount = articleUpCount;
                                this.articleData[i].articleIsUp = !this.articleData[i].articleIsUp;
                                return;
                            }
                        }
                    }
                });
            }
            ,
//文章踩赞
            articleDown(row) {
                if (row.articleIsUp == true) {
                    this.$message.error("请取消点赞后再进行踩赞");
                    return;
                }
                let articleId = row.articleId;
                let params = new URLSearchParams();
                params.append("op", "articleDown");
                params.append("articleId", articleId);
                axios.post(articleUrl, params).then(res => {
                    if (res.data.code == '500') {
                        this.$message.error(res.data.message);
                        return;
                    } else {
                        let articleDownCount = res.data.data;
                        let len = this.articleData.length;
                        for (let i = 0; i < len; i++) {
                            if (this.articleData[i].articleId == articleId) {
                                this.articleData[i].articleDownCount = articleDownCount;
                                this.articleData[i].articleIsDown = !this.articleData[i].articleIsDown;
                                return;
                            }
                        }
                    }
                });
            }
            ,
            handleClick(tab, event) {
                if (tab.index == 0) {
                    this.handleOpen2("1")
                }
            }
            ,
//搜索文章
            searchKeyWord() {
                if (this.searchText == null || this.searchText.trim() == '') {
                    this.$message({
                        showClose: true,
                        message: '空数据不提供搜索',
                        type: 'warning',
                        center: true
                    });
                    return;
                }
                this.classify_index = "8";
                this.index_curPage = 1;
                let params = new URLSearchParams();
                params.append("op", "searchArticles");
                params.append("keywords", this.searchText);
                params.append("curPage", this.index_curPage);
                axios.post(articleUrl, params).then(res => {
                    if (res.data.data.total == 0) {
                        this.$message.info("---很抱歉，没有相关数据!---");
                    } else {
                        this.index_article_total = res.data.data.total;
                        this.articleData = res.data.data.article;
                    }
                });
            }
            ,
//通过审核文章
            passAndNotPassAuditArticle(type) {
                if (this.hasNewAuditArticle == false) {
                    this.$message.info("---暂时没有新的秘密!---");
                    return;
                }
                let params = new URLSearchParams();
                params.append("op", "passAndRefusedArticle");
                params.append("articleId", this.auditArticle.articleId);
                params.append("type", type);
                axios.post(articleUrl, params).then(res => {
                        let msg = type == "pass" ? "寄存成功" : "感谢为网络净化出一份力";
                        this.$message.success(msg);
                        this.getAuditArticle();
                    }
                );
            }
            ,
//获取待审核的文章
            getAuditArticle() {
                axios.post(articleUrl + "?op=auditArticle").then(res => {
                    if (res.data.code == '500') {
                        if (this.audit != false) {
                            this.$message.info("---暂时没有新的秘密!---");
                        }
                        this.auditArticle.articleContent = "---暂时没有新的秘密!---";
                        this.hasNewAuditArticle = false;
                    } else {
                        this.hasNewAuditArticle = true;
                        this.auditArticle = res.data.data;
                    }
                });
            }
            ,
            handleCurrentChange(val) {
                let type;
                if (this.classify_index == "1") {
                    type = "hot";
                } else if (this.classify_index == "2-1") {
                    type = "essence-24";
                } else if (this.classify_index == "2-2") {
                    type = "essence-7";
                } else if (this.classify_index == "2-3") {
                    type = "essence-30";
                } else if (this.classify_index == "3") {
                    type = "new";
                } else if (this.classify_index == "7") {
                    type = "label";
                    this.getArticleBySomeLabel(type);
                    this.smoothscroll();
                    return;
                } else if (this.classify_index == "8") {
                    let params = new URLSearchParams();
                    params.append("op", "searchArticles");
                    params.append("keywords", this.searchText);
                    params.append("curPage", this.index_curPage);
                    axios.post(articleUrl, params).then(res => {
                        if (res.data.data.total == 0) {
                            this.$message.info("---很抱歉，没有相关数据!---");
                        } else {
                            this.index_article_total = res.data.data.total;
                            this.articleData = res.data.data.article;
                        }
                    });
                    return;
                }
                this.getArticleBySome(type, null, null);
                this.smoothscroll();
            },
            getArticleBySomeLabel(type) {
                let params = new URLSearchParams();
                params.append("op", "getArticleBySome");
                params.append('type', type);
                params.append('label', this.searchLabel);
                params.append('curPage', this.index_curPage);
                axios.post(articleUrl, params).then(res => {
                    this.index_article_total = res.data.data.total;
                    this.articleData = res.data.data.article;
                    this.articleIsLoading = false;
                });
            },
            getArticleBySome(type, userId, status) {
                let params = new URLSearchParams();
                if (userId != null && userId != '') {
                    params.append('userId', userId);
                    params.append('status', status);
                }
                params.append("op", "getArticleBySome");
                params.append('type', type);
                params.append('curPage', this.index_curPage);
                axios.post(articleUrl, params).then(res => {
                    this.index_article_total = res.data.data.total;
                    this.articleData = res.data.data.article;
                    this.articleIsLoading = false;
                });
            }
            ,
            publishedArticle() {

                if (this.articleContent.trim() == '' || this.articleContent.trim().length < 10) {
                    this.$message.error("内容过少！");
                    return;
                }
                if (this.valCode == '' || this.valCode.length < 4) {
                    this.$message.error("验证码不正确！");
                    return;
                }
                if (this.articleLabels.trim().split(" ").length > 3) {
                    this.$message.error("标签不能多于3个！");
                    return;
                }
                let params = new URLSearchParams()
                params.append("op", "checkValCode");
                params.append("valCode", this.valCode);
                axios.post(userUrl, params).then(res => {
                    if (res.data.code != '200') {
                        this.$message.error("验证码不正确！");
                        return;
                    } else {
                        let params = new URLSearchParams()
                        params.append("op", "insert");
                        params.append("articleContent", this.articleContent);
                        let articleContent = "<p><span style='color:red;'>[待审核]</span></p>" + this.articleContent;
                        params.append("articleLabel", this.articleLabels.trim());
                        let articleLabel = this.articleLabels.trim();
                        axios.post(articleUrl, params).then(res => {
                            if (res.data.code == '200') {
                                this.$message.success("发布成功，等待审核后发布！");
                                this.articleLabels = '';
                                this.articleContent = '';
                                this.valCode = '';
                                this.published = false;
                                let article = {
                                    articleContent: articleContent,
                                    articleDownCount: 0,
                                    articleIsDown: false,
                                    articleIsUp: false,
                                    articleLabel: articleLabel,
                                    articleLabels: articleLabel.split(" ").length > 0 && articleLabel.split(" ")[0] != '' ? articleLabel.split(" ") : [],
                                    articleStatus: "0",
                                    articleUpCount: 0,
                                }
                                this.articleData.unshift(article);
                            } else {
                                this.$message.error("发布失败，稍后再试！");
                                this.refreshVarCode();
                            }
                        });
                    }
                });
            }
            ,
//刷新验证码
            refreshVarCode() {
                let tmpImage = new Image();
                tmpImage.src = '/treeHole/varifyCode.action?t=' + Math.random() + Math.random();
                document.getElementById('varifyCode').src = tmpImage.src;
            }
            ,
            handleOpen2(index) {
                this.index_curPage = 1;
                this.classify_index = index;
                if (this.classify_index == '6') {
                    this.getUserMayBeLike();
                    return;
                }
                let type;
                let flag = false;
                if (this.classify_index == "1") {
                    type = "hot";
                    flag = true;
                } else if (this.classify_index == "2-1") {
                    type = "essence-24";
                    flag = true;
                } else if (this.classify_index == "2-2") {
                    type = "essence-7";
                    flag = true;
                } else if (this.classify_index == "2-3") {
                    type = "essence-30";
                    flag = true;
                } else if (this.classify_index == "3") {
                    type = "new";
                    flag = true;
                }
                if (flag == true) {
                    this.getArticleBySome(type, null, null);
                }
                if (index == 5) {
                    if (this.userIsLogin == false) {
                        window.location.href = "login.html";
                        return;
                    }
                    this.published = true;
                    setTimeout(this.refreshVarCode, 100)
                }
                if (index == 4) {
                    this.audit = true;
                    setTimeout(this.getAuditArticle, 500)
                }
            }
            ,
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {
                    });
            }
            ,
            changePaw() {
                let params = new URLSearchParams();
                params.append("op", "update");
                params.append("userPassword", this.userPawInforform.newPaw);
                axios.post(userUrl, params).then(res => {
                    if (res.data.code !== "200") {
                        this.$message.error("修改失败，请重试！");
                        return;
                    }
                    this.$message.success("修改成功！");
                    this.userPawInforform.newPaw = '';
                    this.userPawInforform.oldPaw = '';
                });

            }
            ,
//保存信息
            sendEditInfo() {
                var params = new URLSearchParams()
                params.append("op", "update");
                params.append("userId", this.userInfoById.userId);
                params.append("userName", this.userInfoById.userName);
                params.append("userEmail", this.userInfoById.userEmail);
                params.append("userTelephoneNumber", this.userInfoById.userTelephoneNumber);
                params.append("userSex", this.userInfoById.userSex);
                params.append("userIntroduce", this.userInfoById.userIntroduce);
                axios.post(userUrl, params).then(res => {
                    if (res.data.code != '200') {
                        this.$message.error("修改失败，请重试！");
                        return;
                    }
                    this.isEdit = false;
                    this.$message.success("修改成功！");
                    api.refresh();
                });
            }
            ,
            edit() {
                this.isEdit = !this.isEdit;
            }
            , sleep(numberMillis) {
                var now = new Date();
                var exitTime = now.getTime() + numberMillis;
                while (true) {
                    now = new Date();
                    if (now.getTime() > exitTime)
                        return;
                }
            },
            handleOpen(index) {
                if (index != 4 && this.isOwnFace == false) {
                    this.isOwnFace = true;
                    this.closeCamera();
                }
                this.userIndex = index;
                if (index == 1) {
                    this.getUserInfoById(this.userId);
                    return;
                } else if (index == 2) {
                    //已经通过审核的文章
                    this.getOwnerArticleByType(1);
                } else if (index == 3) {
                    this.ownerCommentCurPage = 1;
                    //全部的评论
                    this.getOwnerArticleComments();
                } else if (index == 4) {
                    this.checkUserIsOwnerFace();
                }
            },
            checkUserIsOwnerFace() {
                let params = new URLSearchParams();
                params.append("op", "checkUserIsOwnerFace");
                params.append("userId", this.userId);
                axios.post(userUrl, params).then(res => {
                    if (res.data.code == '200') {
                        //说明用户已经录入过了
                        this.isOwnFace = true;
                    } else {
                        this.isOwnFace = false;
                        this.callCamera();
                    }
                });
            },
            callCamera() {
                try {
                    this.isOwnFace = false;
                    this.openFail = false;
                    navigator.mediaDevices.getUserMedia({
                        video: true
                    }).then(success => {
                        this.$refs['video'].srcObject = success;
                        this.$refs['video'].play()
                    }).catch(error => {
                        this.openFail = false;
                        this.$message({
                            message: '摄像头开启失败，请检查摄像头是否可用！由于浏览器安全策略，开启摄像功能只支持https协议。解决方法:使用谷歌浏览器，并参考博文：https://www.cnblogs.com/aaronguo/p/14204962.html',
                            center: true,
                            type: 'warning',
                            duration: 20000,
                            showClose: true
                        });
                    })
                } catch (e) {
                    this.openFail = true;
                    this.isOwnFace = true;
                    this.$message({
                        message: '摄像头开启失败，请检查摄像头是否可用！由于浏览器安全策略，开启摄像功能只支持https协议。解决方法:使用谷歌浏览器，并参考博文：https://www.cnblogs.com/aaronguo/p/14204962.html',
                        center: true,
                        type: 'warning',
                        duration: 20000,
                        showClose: true
                    });
                }
            },
            uploadImg() {
                let ctx = this.$refs['canvas'].getContext('2d');
                ctx.drawImage(this.$refs['video'], 0, 0, 400, 300);
                let imgBase64 = this.$refs['canvas'].toDataURL('image/jpeg', 0.7);
                let str = imgBase64.replace('data:image/jpeg;base64,', '');
                let params = new URLSearchParams();
                params.append("op", "addFace");
                params.append("base64", str);
                params.append("userId", this.userId);
                axios.post(userUrl, params).then(res => {
                    if (res.data.code == '200') {
                        this.$message.success("录入成功");
                        this.isOwnFace = true;
                        this.closeCamera();
                    } else {
                        this.$message.error(res.data.message);
                    }
                });
            },
            openUserInfoCenter() {
                this.personalCenter = true;
                if (this.userIndex == 4) {
                    this.checkUserIsOwnerFace();
                }
            },
            closeUserInfoCenter() {
                if (this.isOwnFace == false) {
                    this.closeCamera();
                }
            }
            ,
            closeCamera() {
                if (!this.$refs['video'].srcObject) return;
                let stream = this.$refs['video'].srcObject;
                let tracks = stream.getTracks();
                tracks.forEach(track => {
                    track.stop();
                });
                this.$refs['video'].srcObject = null;
            }
            ,

            getUserMedia(constraints, success, error) {
                if (navigator.mediaDevices.getUserMedia) {
                    //最新的标准API
                    navigator.mediaDevices.getUserMedia(constraints).then(success => {
                        // 摄像头开启成功
                        this.$refs['video'].srcObject = success;
                        // 实时拍照效果
                        this.$refs['video'].play()
                    }).catch(error);

                } else if (navigator.webkitGetUserMedia) {
                    //webkit核心浏览器
                    navigator.webkitGetUserMedia(constraints, success, error)
                } else if (navigator.mozGetUserMedia) {
                    //firfox浏览器
                    navigator.mozGetUserMedia(constraints, success, error);
                } else if (navigator.getUserMedia) {
                    //旧版API
                    navigator.getUserMedia(constraints, success, error);
                }
            }
            ,

            getUserInfoById(userId) {
                let params = new URLSearchParams();
                params.append("op", "getUserInfo");
                params.append("userId", userId);
                axios.post(userUrl, params).then(res => {
                    if (res.data.code == '200') {
                        this.userInfoById = res.data.data;
                    }
                });
            }
            ,
//设置Cookie
            setUserInfoCookie(res) {
                res = res.data.data;
                api.setCookie("loginUser.userId", res.userId);
                api.setCookie("loginUser.userName", res.userName);
                api.setCookie("loginUser.userProfilePhoto", res.userProfilePhoto);
                api.setCookie("loginUser.userRegistrationTime", res.userRegistrationTime);
                api.setCookie("loginUser.userTelephoneNumber", res.userTelephoneNumber);
            }
            ,
//从Token中获取用户信息
            setLoginUserInfo() {
                this.userId = api.getCookie("loginUser.userId");
                this.userName = api.getCookie("loginUser.userName");
                this.userAvatarUrl = api.getCookie("loginUser.userProfilePhoto");
            }
            ,
//处理头像成功
            handleAvatarSuccess(res, file) {
                if (res.code != "200") {
                    return this.$message.error("上传失败！");
                }
                this.$message.success("上传成功！");
                this.userAvatarUrl = res.data;
                api.setCookie("loginUser.userProfilePhoto", res.data);
            }
            ,
//上传头像前
            beforeAvatarUpload(file) {
                this.myHeaders.Authorization = api.getCookie("token");
                const isJPG = file.type === "image/jpeg";
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error("上传头像图片只能是 JPG 格式!");
                }
                if (!isLt2M) {
                    this.$message.error("上传头像图片大小不能超过 2MB!");
                }
                return isJPG && isLt2M;
            }
            ,
//当金钱改变的时候触发
            moneyChange() {
                this.refreshCode(2);
            }
            ,
//打赏金额
            formatTooltip(val) {
                return val + "￥";
            }
            ,
            logout() {
                let params = new URLSearchParams();
                params.append("op", "loginOut");
                axios.post(userUrl, params).then(res => {
                    if (res.data.code == '200') {
                        this.$message({
                            type: "success",
                            message: '退出成功!',
                            center: true
                        });
                        this.userIsLogin = false;
                        api.clearAllCookie();
                        api.refresh();
                    } else {
                        this.$message.error("退出失败！");
                    }
                });
            }
            ,
            go() {
            }
            ,
//制作二维码
            makeQrcode() {
                $('#qrcode').html('');
                $('#qrcode').qrcode({
                    render: 'table',
                    height: 165,
                    width: 165,
                    text: this.qrCode,
                    typeNumber: -1, // 计算模式
                    correctLevel: 2, // 二维码纠错级别
                    background: "#ffffff", // 背景颜色
                    foreground: "#000000" // 二维码颜色
                })
            }
            ,
//刷新二维码
            refreshCode(type) {
                if (type == 1) {
                    if (this.isShowTooltip == true) {
                        return;
                    }
                }
                let params = new URLSearchParams();
                params.append("op", "getQrCode");
                params.append("orderAmount", this.money);
                axios.post('/treeHole/pay.action', params).then(res => {
                    if (res.data.code == '200') {
                        this.qrCode = res.data.data.qrCode;
                        this.orderId = res.data.data.orderId;
                        this.makeQrcode();
                        clearInterval(timingQrcode);
                        timingQrcode = setInterval(this.timingQrcodeCheck, 2000)
                    } else {
                        this.$message({
                            type: "error",
                            message: '获取验证码失败',
                            center: true
                        });
                    }
                })
            }
            ,
//定时刷新二维码
            timingQrcodeCheck() {
                if (this.isShowTooltip == false) {
                    //说明用户收起了二维码
                    qrcodeTime = 60 * 14;
                    clearInterval(timingQrcode);
                    return;
                }
                if (qrcodeTime <= 1) {
                    //说明二维码过期了
                    this.refreshCode(2);
                    qrcodeTime = 60 * 14;
                } else {
                    qrcodeTime = qrcodeTime - 2;
                    this.checkPay();
                }
            }
            ,
//检测支付情况
            checkPay() {
                let params = new URLSearchParams();
                params.append("op", "orderIsPay");
                params.append("orderId", this.orderId);
                axios.post('/treeHole/pay.action', params).then(res => {
                    if (res.data.data == true) {
                        //说明支付成功
                        this.$message({
                            type: "success",
                            message: '老板大气，感谢打赏',
                            center: true
                        });
                        clearInterval(timingQrcode);
                        this.refreshCode(2);
                    }
                });
            }
            ,
//检查用户是否登录
            checkUserIsLogin() {
                let params = new URLSearchParams();
                params.append("op", "checkIsLogin");
                axios.post(userUrl, params).then(res => {
                    if (res.data.code == "200") {
                        this.setUserInfoCookie(res)
                        this.setLoginUserInfo();
                        this.userIsLogin = true;
                    } else {
                        api.clearAllCookie();
                        this.userIsLogin = false;
                    }
                });
            }
        },
        mounted() {
            this.checkUserIsLogin();
            // this.getAllReportLabels();
            this.getArticleBySome("hot");
            // this.getAuditArticle();
            this.initWebSocket();
        }
        ,
        destroyed() {
            this.websock.close(); // 离开路由之后断开websocket连接
        },
    })
;